package java8;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/19 22:15
 * <p>
 * Optional是一个容器
 * <p>
 * Optional<T>.of()方法中，如果传入了一个null，就会立即抛出异常信息，便于定位发生NPE的位置
 */
public class TestOptional {

    private static ReadWriteLock lock = new ReentrantReadWriteLock();

    @Test
    public void test1() {
        Optional<Employee> op = Optional.of(new Employee());
        Employee emp = op.get();

        System.out.println(emp);

        List<String> list = Arrays.asList("aa", "bb", "cc");

    }

    @Test
    public void test2() {
        Optional<Employee> op = Optional.empty();
        System.out.println(op.get());
    }

    @Test
    public void test3() {
        Optional<Employee> op = Optional.ofNullable(null);
        op.orElse(new Employee("test", 23, 324324, Employee.Status.BUSY));
        if (op.isPresent()) {
            System.out.println(op.get());
        }

        Employee emp = op.orElseGet(() -> new Employee());
        System.out.println(emp);
    }

    @Test
    public void test4() {
        Optional<Employee> op = Optional.ofNullable(new Employee("test", 23, 324324, Employee.Status.BUSY));
        Optional<String> str = op.map(e -> e.getName());
        System.out.println(str.get());
    }

    @Test
    public void test5() {
        System.out.println(getGodnessName(null));
        Man man = new Man();
        System.out.println(getGodnessName(man));
    }

    private String getGodnessName(Man man) {
        Optional<Man> op = Optional.ofNullable(man);
        return op.orElse(new Man())
                .getGodness()
                .orElse(new Godness("苍老师"))
                .getName();
    }
}
